package com.example.server.controller;

import com.example.server.common.Result;
import com.example.server.entity.RecentPlayedScript;
import com.example.server.entity.Role;
import com.example.server.entity.Scene;
import com.example.server.entity.Script;
import com.example.server.service.ScriptService;
import com.example.server.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/scripts")
public class ScriptController {
    @Autowired
    private ScriptService scriptService;

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    // 添加剧本
    @PostMapping("/add")
    public Result addScript(@RequestParam String title,
                            @RequestParam String author,// author不应该由用户输入，而是前端直接传入当前用户的名称（username）
                            @RequestParam String content,
                            @RequestParam String tags) {
        try {
            //默认图片路径
            String imageUrl = "http://" + ip + ":" + port + "/uploads/images/default.jpg";
            return Result.success(scriptService.addScript(title, author, imageUrl, content, tags));
        } catch (Exception e) {
            return Result.error("剧本添加失败");
        }
    }

    // 分页查剧本
    @GetMapping("/all")
    public Result getAllScripts() {
        try {
            // System.out.println("hello");
            List<Script> scripts = scriptService.getAllScripts();
            return Result.success(scripts);
        } catch (Exception e) {
            return Result.error("查询所有剧本失败");
        }
    }

    //上传剧本图片
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("id") Integer id, @RequestParam("image") MultipartFile image) {
        try {
            String imageUrl = "http://" + ip + ":" + port + "/"
                    + FileUploadUtil.saveImageFile(image, "images", String.valueOf(id), "jpg");
            scriptService.uploadImage(id, imageUrl);
            return Result.success(imageUrl);
        } catch (Exception e) {
            return Result.error("图片上传失败：" + e.getMessage());
        }
    }

    // 根据主键查剧本
    @GetMapping("/{id}")
    public Result getScriptById(@PathVariable Integer id) {
        try {
            Script script = scriptService.getScriptById(id);
            return Result.success(script);
        } catch (Exception e) {
            return Result.error("查找失败");
        }
    }

    // 根据名称模糊匹配剧本
    @GetMapping("/search")
    public Result getScriptsByTitle(@RequestParam String title) {
        try {
            List<Script> scripts = scriptService.getScriptsByTitle(title);
            return Result.success(scripts);
        } catch (Exception e) {
            return Result.error("没有匹配结果");
        }
    }

    // 查询用户id最近游玩剧本
    @GetMapping("/recent/{id}")
    public Result getRecentPlayedScripts(@PathVariable Integer id) {
        try {
            System.out.println(id);
            List<RecentPlayedScript> scripts = scriptService.getRecentPlayedScripts(id);
            System.out.println(scripts);
            return Result.success(scripts);
        } catch (Exception e) {
            return Result.error("查找失败");
        }
    }

    // 根据作者名（也就是用户名）拿到他上传的剧本
    @GetMapping("/author/{author}")
    public Result getScriptsByAuthor(@PathVariable String author) {
        try {
            List<Script> scripts = scriptService.getScriptsByAuthor(author);
            return Result.success(scripts);
        } catch (Exception e) {
            return Result.error("作者名可能错误");
        }
    }

    // 某用户可以修改自己上传的剧本
    @PutMapping("/update")
    public Result updateScript(@RequestParam Integer id,// id指剧本id
                               @RequestParam String title,
                               @RequestParam String content,
                               @RequestParam String tags) {
        try {
            scriptService.updateScript(id, title, content, tags);
            return Result.success();
        } catch (Exception e) {
            return Result.error("更新剧本失败");
        }
    }

    //某用户可以直接删除自己上传的剧本
    @DeleteMapping("/delete/{id}")
    public Result deleteScriptById(@PathVariable Integer id) {
        try {
            scriptService.deleteScriptByID(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除失败");
        }
    }

    // 添加角色
    @PostMapping("/roles/add")
    public Result addRole(@RequestParam Integer scriptId,
                          @RequestParam String name,
                          @RequestParam String description,
                          @RequestParam String traits) {
        try {
            scriptService.addRole(scriptId, name, description, traits);
            return Result.success();
        } catch (Exception e) {
            return Result.error("添加角色失败");
        }
    }

    // 根据主键查角色
    @GetMapping("/roles/{id}")
    public Result getRoleById(@PathVariable Integer id) {
        try {
            Role role = scriptService.getRoleById(id);
            return Result.success(role);
        } catch (Exception e) {
            return Result.error("未查找到相关角色");
        }
    }

    // 根据剧本id查角色
    @GetMapping("/roles/script/{scriptId}")
    public Result getRolesByScriptId(@PathVariable Integer scriptId) {
        try {
            List<Role> roles = scriptService.getRolesByScriptId(scriptId);
            return Result.success(roles);
        } catch (Exception e) {
            return Result.error("未查找到剧本相关角色");
        }
    }

    // 更新角色
    @PutMapping("/roles/update")
    public Result updateRole(@RequestParam Integer id,
                             @RequestParam Integer scriptId,
                             @RequestParam String name,
                             @RequestParam String description,
                             @RequestParam String traits) {
        try {
            scriptService.updateRole(id, scriptId, name, description, traits);
            return Result.success();
        } catch (Exception e) {
            return Result.error("角色更新失败");
        }
    }

    // 删除角色
    @DeleteMapping("/roles/delete/{id}")
    public Result deleteRoleById(@PathVariable Integer id) {
        try {
            scriptService.deleteRoleById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("角色删除失败");
        }
    }

    // 添加场景
    @PostMapping("/scenes/add")
    public Result addScene(@RequestParam Integer scriptId,
                           @RequestParam String description) {
        System.out.println(scriptId + description);
        try {
            System.out.println("hello scenes add");
            scriptService.addScene(scriptId, description);
            //System.out.println(description);
            return Result.success();
        } catch (Exception e) {
            return Result.error("添加场景失败");
        }
    }

    // 根据主键查场景
    @GetMapping("/scenes/{id}")
    public Result getSceneById(@PathVariable Integer id) {
        try {
            Scene scene = scriptService.getSceneById(id);
            return Result.success(scene);
        } catch (Exception e) {
            return Result.error("未查找到相关场景");
        }
    }

    // 根据剧本id查场景
    @GetMapping("/scenes/script/{scriptId}")
    public Result getScenesByScriptId(@PathVariable Integer scriptId) {
        try {
            Scene scenes = scriptService.getScenesByScriptId(scriptId);
            return Result.success(scenes);
        } catch (Exception e) {
            return Result.error("未查找到剧本相关场景");
        }
    }

    // 更新场景
    @PutMapping("/scenes/update")
    public Result updateScene(@RequestParam Integer id,
                              @RequestParam String description) {
        try {
            scriptService.updateScene(id, description);
            return Result.success();
        } catch (Exception e) {
            return Result.error("场景更新失败");
        }
    }

    // 删除场景
    @DeleteMapping("/scenes/delete/{id}")
    public Result deleteSceneById(@PathVariable Integer id) {
        try {
            scriptService.deleteSceneById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("场景删除失败");
        }
    }
}
